import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Notice from '../components/notice/Notice.vue'
import Teacher from '../components/user/Teacher.vue'
import Student from '../components/user/Student.vue'
import Query from '../components/score/Query.vue'
import Edit from '../components/score/Edit.vue'
import Lesson from '../components/lesson/Lesson.vue'
import Public from '../components/notice/Public.vue'
import Statistics from '../components/statistics/Statistics.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/notice',
    children: [
      { path: '/notice', component: Notice },
      { path: '/teacher', component: Teacher },
      { path: '/student', component: Student },
      { path: '/search', component: Query },
      { path: '/edit', component: Edit },
      { path: '/lesson', component: Lesson },
      { path: '/public', component: Public },
      { path: '/statistics', component: Statistics }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页，直接放行
  if (to.path === '/login') return next()
  // 从localStorage中获取身份令牌
  const isToken = localStorage.getItem('token')
  // 如果没有身份令牌说明没有登录，强制跳转到登录页
  if (!isToken) return next('/login')
  // 如果已经登录,放行
  next()
})

export default router
